package com.nervenets.web.controller.promotion;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.BaseController;
import com.nervenets.web.controller.IdTokenParams;
import com.nervenets.web.entity.KeyValue;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.dao.PromotionDao;
import com.nervenets.web.hibernate.domain.Promotion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(value = "活动接口v1", description = "活动类接口")
@RestController
@RequestMapping("/api/v1/promotion")
public class PromotionController extends BaseController {
    @Resource
    private PromotionDao promotionDao;

    @ApiOperation("活动列表")
    @PostMapping("/list")
    public String list(@RequestBody PromotionPagingParams params) {
        final Set<ConstraintViolation<PromotionPagingParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Specification<Promotion> specification = (Specification<Promotion>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(params.getName())) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + params.getName() + "%"));
            }
            switch (params.getEnable()) {
                case 0:
                    break;
                case 1:
                    predicates.add(criteriaBuilder.isTrue(root.get("enable")));
                    break;
                case 2:
                    predicates.add(criteriaBuilder.isFalse(root.get("enable")));
                    break;
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        final Page<Promotion> pages = promotionDao.findAll(specification, PageRequest.of(params.getPage(), params.getLimit(), new Sort(Sort.Direction.DESC, "queue")));

        return successMessage(pages.getContent(), new KeyValue("page", params.getPage()), new KeyValue("total", pages.getTotalElements()));
    }

    @ApiOperation("活动详情")
    @PostMapping("/detail")
    public String detail(@RequestBody IdTokenParams params) {
        final Set<ConstraintViolation<IdTokenParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Promotion promotion = promotionDao.findById(params.getTargetId()).orElse(null);
        if (null == promotion) return errorMessage(MessageCode.code_404, "您要查看的活动不存在");

        return successMessage(promotion);
    }

    @ApiOperation("活动添加或编辑")
    @PostMapping("/edit")
    public String edit(@RequestBody PromotionEditParams params) {
        final Set<ConstraintViolation<PromotionEditParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Promotion promotion = new Promotion();
        if (params.getPromotionId() > 0) {
            promotion = promotionDao.findById(params.getPromotionId()).orElse(null);
            if (null == promotion) return errorMessage(MessageCode.code_404, "您编辑的活动不存在");
        }

        promotion.setName(params.getName());
        promotion.setCover(params.getCover());
        promotion.setContent(params.getContent());
        promotion.setDescription(params.getDescription());
        promotion.setEnable(params.isEnable());
        promotion.setQueue(params.getQueue());
        promotionDao.save(promotion);

        return successMessage();
    }

    @ApiOperation("活动删除")
    @PostMapping("/del")
    public String del(@RequestBody IdTokenParams params) {
        final Set<ConstraintViolation<IdTokenParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Promotion promotion = promotionDao.findById(params.getTargetId()).orElse(null);
        if (null == promotion) return errorMessage(MessageCode.code_404, "您要删除的活动不存在");

        promotionDao.delete(promotion);

        return successMessage();
    }
}
